// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/tool/trace/table_scan_replayer.h>

#include <pollux/connectors/hive/hive_connector_split.h>
#include <pollux/exec/operator_trace_reader.h>
#include <pollux/exec/trace_util.h>
#include <pollux/testing/exec/util/assert_query_builder.h>
#include <pollux/plan/plan_builder.h>
#include <pollux/tool/trace/trace_replay_task_runner.h>

using namespace kumo::pollux;
using namespace kumo::pollux::exec;
using namespace kumo::pollux::exec::test;

namespace kumo::pollux::tool::trace {

RowVectorPtr TableScanReplayer::run(bool copyResults) {
  TraceReplayTaskRunner traceTaskRunner(createPlan(), createQueryCtx());
  auto [task, result] = traceTaskRunner.maxDrivers(driverIds_.size())
                            .splits(replayPlanNodeId_, getSplits())
                            .run(copyResults);
  printStats(task);
  return result;
}

core::PlanNodePtr TableScanReplayer::createPlanNode(
    const core::PlanNode* node,
    const core::PlanNodeId& nodeId,
    const core::PlanNodePtr& /*source*/) const {
  const auto scanNode = dynamic_cast<const core::TableScanNode*>(node);
  POLLUX_CHECK_NOT_NULL(scanNode);
  return std::make_shared<core::TableScanNode>(
      nodeId,
      scanNode->outputType(),
      scanNode->tableHandle(),
      scanNode->assignments());
}

std::vector<exec::Split> TableScanReplayer::getSplits() const {
  std::vector<std::string> splitInfoDirs;
  for (const auto driverId : driverIds_) {
    splitInfoDirs.push_back(exec::trace::getOpTraceDirectory(
        nodeTraceDir_, pipelineIds_.front(), driverId));
  }
  const auto splitStrs =
      exec::trace::OperatorTraceSplitReader(
          splitInfoDirs, memory::MemoryManager::getInstance()->tracePool())
          .read();

  std::vector<exec::Split> splits;
  for (const auto& splitStr : splitStrs) {
    melon::Dynamic splitInfoObj = melon::parseJson(splitStr);
    const auto split =
        ISerializable::deserialize<connector::hive::HiveConnectorSplit>(
            splitInfoObj);
    splits.emplace_back(
        std::const_pointer_cast<connector::hive::HiveConnectorSplit>(split));
  }
  return splits;
}
} // namespace kumo::pollux::tool::trace
